package com.woniu.gateway.exception;

import cn.hutool.json.JSONUtil;
import com.woniu.core.exception.WoniuxyException;
import com.woniu.core.util.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
//响应的全局异常处理
public class ExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ex.printStackTrace();
        //设置上下文格式
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Result<String> resultUtil=null;
        if(ex instanceof WoniuxyException){
            WoniuxyException we = (WoniuxyException) ex;
            resultUtil= Result.getResult(String.class).setCode(we.getCode()).setMsg(we.getMessage());
        }else {
            resultUtil= Result.getResult(String.class).setCode(500).setMsg("系统错误");
        }
        String string = JSONUtil.parse(resultUtil).toString();
        return exchange.getResponse().writeWith(Mono.fromSupplier(()->{
            return exchange.getResponse().bufferFactory().wrap(string.getBytes());
        }));
    }
}
